package com.golddaymicromall.activity.salemanager;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.TePinInfo;
import com.golddaymicromall.util.ActivityController;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import rx.android.schedulers.AndroidSchedulers;

public class ConfirmPayPwdActivity extends BaseActivity implements View.OnClickListener {

    private TextView mCustomerid;
    private EditText mPayPassword;
    private Button mConfirmPay;
    private LinearLayout mPayPasswordBack;

    String id;
    private String customerid;
    private String orderId;

    String logid;
    String msaleflag;

    private TextView mOffTextView;
    private Handler mOffHandler;
    private Timer mOffTime;
    private Dialog mDialog;
    List<TePinInfo> list;
    String text;
    String flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_pay_pwd);
        initView();
    }

    private void initView() {
        mCustomerid = (TextView) findViewById(R.id.pay_customerid);
        mPayPassword = (EditText) findViewById(R.id.pay_password);
        mConfirmPay = (Button) findViewById(R.id.querenzhifu);
        mPayPasswordBack = (LinearLayout) findViewById(R.id.paypasswordback);
        mConfirmPay.setOnClickListener(this);
        mPayPasswordBack.setOnClickListener(this);
        id = customerid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        customerid = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        msaleflag = SPUtils.get(getApplicationContext(), "saleflag", "").toString();
        mCustomerid.setText(customerid);
        orderId = getIntent().getStringExtra("orderId");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.paypasswordback:
                finish();
                break;
            case R.id.querenzhifu:
                attemptValidatePayment();
                MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                        SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "二次进货，验证支付，订单编号：" + orderId);
                break;
        }
    }

    private void attemptShengtepin() {
        //获取本地数据
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.oristg");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("logid", logid);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            if (Integer.parseInt(result) == 1) {
                                Toast.makeText(ConfirmPayPwdActivity.this, "您已申请特聘", Toast.LENGTH_SHORT).show();
                            } else {
                                attemptgetinfo();
                            }
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();

                    }
                },throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    //支付
    public void attemptPayment() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.payment");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", orderId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (!"".equals(result)) {
                        if ("1".equals(result)) {
                            if (msaleflag.equals("1")) {
                                SPUtils.put(getApplicationContext(),"saleflag","0");
                                attemptShengtepin();
                            } else {
                                finish();
                                ActivityController.getInstance().popActivity();
                                ActivityController.getInstance().popActivity();
                            }
                        } else {
                            Toast.makeText(ConfirmPayPwdActivity.this, "余额不足,请充值", Toast.LENGTH_SHORT).show();
                        }
                    }
                },throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    //验证密码
    public void attemptValidatePayment() {
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        String paypwd = mPayPassword.getText().toString();
        if ("".equals(paypwd)) {
            Toast.makeText(this, "支付密码不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.password.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", logid);
        form.put("trandword", paypwd);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();

                    if (!"".equals(result)) {
                        result = result.replace(".0", "");
                        if (Integer.parseInt(result) == 0) {
                            Toast.makeText(ConfirmPayPwdActivity.this, "支付密码错误!", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (Integer.parseInt(result) == 1) {
                            attemptPayment();
                            MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                                    SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "二次进货，支付成功，订单编号：" + orderId);
                        } else if (Integer.parseInt(result) == 2) {
                            Toast.makeText(ConfirmPayPwdActivity.this, "账户异常,请重新输入!", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (Integer.parseInt(result) == 3) {
                            Toast.makeText(ConfirmPayPwdActivity.this, "账户余额不足!", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                },throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });
    }

    public void attemptgetinfo() {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.notice.getxy");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(ConfirmPayPwdActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(ConfirmPayPwdActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            list = JSON.parseArray(result, TePinInfo.class);
                            String content = list.get(0).getContent();
                            String title = list.get(0).getTitle();
                            text = Html.fromHtml(content).toString();
                            timeCountDialog();
                        }
                    } else {
                        Toast.makeText(ConfirmPayPwdActivity.this, "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    public void timeCountDialog() {
        mOffTextView = new TextView(this);
        mOffTextView.setText(text);
        mOffTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
        mDialog = new android.support.v7.app.AlertDialog.Builder(this)
                .setTitle("提示")
                .setCancelable(false)
                .setView(mOffTextView)
                .setPositiveButton("10秒", null)
                .setNegativeButton("暂不申请", null)
                .create();
        mDialog.show();
        mDialog.setCanceledOnTouchOutside(false);
        final Button Positivebutton = ((android.support.v7.app.AlertDialog) mDialog).getButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE);
        final Button Negativebutton = ((android.support.v7.app.AlertDialog) mDialog).getButton(android.support.v7.app.AlertDialog.BUTTON_NEGATIVE);
        Positivebutton.setTextSize(18);
        Positivebutton.setTextColor(getResources().getColor(R.color.colorAccent));
        Negativebutton.setTextSize(18);
        Negativebutton.setTextColor(getResources().getColor(R.color.colorAccent));
        Positivebutton.setOnClickListener(v -> {
            if (Positivebutton.getText().toString().contains("自愿申请")) {
                flag = "1";
                attemptpossinfo();
            }
        });
        Negativebutton.setOnClickListener(v -> {
            flag = "2";
            attemptpossinfo();
        });


        mOffHandler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    //动态显示倒计时
                    Positivebutton.setText(msg.what + "秒");
                } else {
                    //倒计时结束自动关闭
                    if (mDialog != null) {
                        Positivebutton.setText("自愿申请");
                    }
                    mOffTime.cancel();
                }
                super.handleMessage(msg);
            }

        };

        //////倒计时

        mOffTime = new Timer(true);
        TimerTask tt = new TimerTask() {
            int countTime = 10;

            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                mOffHandler.sendMessage(msg);
            }
        };
        mOffTime.schedule(tt, 1000, 1000);
    }

    public void attemptpossinfo() {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.istg");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        if (flag.equals("1")) {
            form.put("customerclassid", "29");
        } else if (flag.equals("2")) {
            form.put("customerclassid", "27");
        }
        form.put("logid", id);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (Integer.parseInt(result) == 1) {
                        if("1".equals(flag)){
                            Toast.makeText(ConfirmPayPwdActivity.this, "申请特聘成功", Toast.LENGTH_SHORT).show();
                            SPUtils.put(ConfirmPayPwdActivity.this, "OrganizationId", "29");
                            mDialog.dismiss();
                            mOffTime.cancel();
                            ActivityController.getInstance().removeActivity(ConfirmPayPwdActivity.this);
                            finish();
                            ActivityController.getInstance().popActivity();
                        }else if("2".equals(flag)){
                            Toast.makeText(ConfirmPayPwdActivity.this, "您尚未申请加入特聘", Toast.LENGTH_SHORT).show();
                            SPUtils.put(ConfirmPayPwdActivity.this, "OrganizationId", "27");
                            mDialog.dismiss();
                            mOffTime.cancel();
                            ActivityController.getInstance().removeActivity(ConfirmPayPwdActivity.this);
                            finish();
                            ActivityController.getInstance().popActivity();
                        }
                    } else {
                        Toast.makeText(ConfirmPayPwdActivity.this, "申请特聘失败", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }
}
